package com.lly.songhigh.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.activity.PlayMusicActivity;
import com.lly.songhigh.activity.SingerDetailActivity;
import com.lly.songhigh.adapter.SingerSingleListViewAdapter;
import com.lly.songhigh.adapter.SingleFragmentListviewAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.SingerSingle;
import com.lly.songhigh.entity.dao.Collection;
import com.lly.songhigh.entity.dao.RecentPlay;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.greendao.DaoSingleton;
import com.lly.songhigh.service.DownloadServices;
import com.lly.songhigh.utils.SharedPreferencesUtils;
import com.lly.songhigh.view.NoScrollListView;
import com.lly.songhigh.view.PublishSelectPicPopupWindow;
import com.lly.songhigh.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class SingleFragment extends BaseFragment implements AdapterView.OnItemClickListener, SingerSingleListViewAdapter.OnMenuClickListener {

    private String url1;
    private VolleySingleton volleySingleton;
    private List<SingerSingle.DataEntity> singer;
    private PublishSelectPicPopupWindow menuWindow;
    private TextView pw_collection, pw_download, pw_share, pw_singer, pw_album, pw_song_info;
    private RelativeLayout alpha_layout;
    private List<MusicInfo> musicInfos;
    private SingerSingleListViewAdapter adapter;
    private NoScrollListView single_listView;
    private SingerSingle.DataEntity dataEntity, downloadEntity;
    private List<Collection> collections;
    private DaoSingleton daoSingleton;

    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private String shareUrl;
    private String path;
    private int downloadCount = 0;
    private ListView singleListView;
    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.single_fragment, null);
        EventBus.getDefault().register(this);
        initView(view);
        initShare();
        QQShare();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        BaseApplication.getInstance().addActivity(getActivity());
        initData();
    }

    private void initView(View view) {
        single_listView = (NoScrollListView) view.findViewById(R.id.single_listView);
        alpha_layout = (RelativeLayout) getActivity().findViewById(R.id.singer_relative_layout);
    }

    private void initData() {
        daoSingleton = DaoSingleton.getInstance();
        volleySingleton = VolleySingleton.getInstance();
        url1 = getArguments().getString("url");
        StringRequest request = new StringRequest(url1, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    SingerSingle result = gson.fromJson(response, SingerSingle.class);
                    if (result != null && result.getData() != null) {
                        singer = result.getData();
                        adapter = new SingerSingleListViewAdapter(getActivity(), singer);
                        single_listView.setAdapter(adapter);
                        single_listView.setOnItemClickListener(SingleFragment.this);
                        adapter.setOnMenuClickListener(SingleFragment.this);

                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onMenuClick(SingerSingle.DataEntity dataEntity) {
        this.dataEntity = dataEntity;
        downloadEntity = dataEntity;
        alpha_layout.setVisibility(View.VISIBLE);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popup_window, null);

        shareUrl = URL.SHARE_SINGLE_START + dataEntity.getSongId() + URL.SHARE_SINGLE_END;
        pw_collection = (TextView) view.findViewById(R.id.pw_collection);
        pw_download = (TextView) view.findViewById(R.id.pw_download);
        pw_share = (TextView) view.findViewById(R.id.pw_share);
        pw_singer = (TextView) view.findViewById(R.id.pw_singer);
        pw_album = (TextView) view.findViewById(R.id.pw_album);
        pw_song_info = (TextView) view.findViewById(R.id.pw_song_info);
        pw_song_info.setText("歌曲：" + dataEntity.getName());
        pw_singer.setText("歌手：" + dataEntity.getSingerName());
        if (dataEntity.getAlbumName() != null && !dataEntity.getAlbumName().equals("")) {
            pw_album.setText("专辑：" + dataEntity.getAlbumName());
        }
        menuWindow = new PublishSelectPicPopupWindow(getActivity(), itemsOnClick, view, alpha_layout);
        menuWindow.showAtLocation(getActivity().findViewById(R.id.detail_toolbar_back),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        collections = daoSingleton.getCollectionById(dataEntity.getSongId());
        if (collections.size() > 0 && collections != null)
            pw_collection.setText("取消收藏");
        else
            pw_collection.setText("收藏");
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.pw_collection:
                    if (!(collections.size() > 0 && collections != null)) {
                        Collection collection = new Collection();
                        collection.setSongName(dataEntity.getName());
                        collection.setDuration(dataEntity.getUrlList().get(0).getDuration());
                        collection.setAlbumId((long) dataEntity.getAlbumId());
                        collection.setPlayUrl(dataEntity.getUrlList().get(0).getUrl());
                        collection.setSingerName(dataEntity.getSingerName());
                        collection.setSongId((long) dataEntity.getSongId());
                        daoSingleton.getCollectionDao().insert(collection);
                        Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_LONG).show();
                    } else {
                        daoSingleton.deleteCollectionById(dataEntity.getSongId());
                        Toast.makeText(getActivity(), "已删除收藏", Toast.LENGTH_LONG).show();
                    }
                    break;
                case R.id.pw_share:
                    mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                    //是否只有已登录用户才能打开分享选择页
                    mController.openShare(getActivity(), false);
                    QQShare();
                    break;
                case R.id.pw_download:

                    EventBus.getDefault().post(new MyEvent.GetFileName(downloadEntity.getName()));
                    if (downloadEntity.getAuditionList().size() == 0) {
                        Toast.makeText(getActivity(), StringResouce.NO_RESOURCES, Toast.LENGTH_SHORT).show();
                    } else {
                        SharedPreferencesUtils.putSharePre(getActivity(), "Download", "SongName",
                                downloadEntity.getName());
                        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_charts_download_listview, null);
                        singleListView = (ListView) view.findViewById(R.id.charts_download_listView);
                        SingleFragmentListviewAdapter singleFragmentListviewAdapter = new SingleFragmentListviewAdapter(downloadEntity.getAuditionList(),
                                getActivity());
                        singleListView.setAdapter(singleFragmentListviewAdapter);
                        builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage(StringResouce.CHOOSE_QUALITY);
                        builder.setView(view);
                        alertDialog = builder.create();
                        alertDialog.show();
                        singleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                startDownloadService();
                                path = downloadEntity.getAuditionList().get(position).getUrl();
                                alertDialog.dismiss();
                                Toast.makeText(getActivity(), StringResouce.START_DOWNLOADING, Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    break;
                case R.id.pw_singer:
                    Intent intent = new Intent(getActivity(), SingerDetailActivity.class);
                    intent.putExtra("singerId", dataEntity.getSingerId());
                    startActivity(intent);
                    break;
            }
        }
    };


    public void onEventMainThread(MyEvent.IsDlding isDlding) {
        if (isDlding.isDownloading()) {
            EventBus.getDefault().post(new MyEvent.DldMessage(downloadEntity.getName(), path));
        }
    }
    public void startDownloadService() {
        Intent i = new Intent(getActivity(), DownloadServices.class);
        getActivity().startService(i);
    }

    private void initShare() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(getActivity(), "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(getActivity(), "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void QQShare() {
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent("第一次分享东西， 好好看");
        //设置分享title
        qqShareContent.setTitle("哈哈哈");
        //设置点击分享内容的跳转连接
        qqShareContent.setTargetUrl(shareUrl);
        //????
        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent("第一次给你分享东西，好好看");
        //设置分享内容的标题
        qzone.setTitle("哈哈哈");
        //设置点击消息的跳转URL
        qzone.setTargetUrl(shareUrl);
        mController.setShareMedia(qzone);



    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SingerSingle.DataEntity dataEntity = (SingerSingle.DataEntity) parent.getItemAtPosition(position);
        if (dataEntity.getUrlList() != null && dataEntity.getUrlList().size() > 0) {
            Intent intent = new Intent(getActivity(), PlayMusicActivity.class);
            daoSingleton.getRecentPlayDao().insert(new RecentPlay(dataEntity.getName(),
                    dataEntity.getSingerName(), dataEntity.getAlbumName(),
                    StringResouce.RESOUCE_NET, dataEntity.getUrlList().get(0).getUrl(),
                    (long)dataEntity.getAlbumId(), dataEntity.getUrlList().get(0).getDuration(),
                    (long)dataEntity.getSongId()));
            musicInfos = new ArrayList<>();
            for (SingerSingle.DataEntity entity : singer) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerId(entity.getSingerId());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setAlbumId((long)entity.getAlbumId());
                    musicInfo.setSongId(entity.getSongId());
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setResouce(StringResouce.RESOUCE_NET);
                    musicInfos.add(musicInfo);
                }
            }
            EventBus.getDefault().post(new MyEvent.DeliverData(musicInfos, dataEntity.getName()));
            startActivity(intent);
        } else {
            Toast.makeText(getActivity(), "由于版权方禁止, 此服务臣妾办不到啊...", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

